<script setup lang="ts">
import { computed, Fragment, h, onBeforeMount, onMounted, ref } from "vue";
import { useColumns } from "./columns";
import { IconifyIconOnline } from "@/components/ReIcon";
import { PlusDialogForm } from "plus-pro-components";
import type { PlusColumn, FieldValues, OptionsRow } from "plus-pro-components";
import {
  createFlower,
  deleteFlower,
  getFlowerTypeOptions,
  updateFlower
} from "@/api/flower";
import { message } from "@/utils/message";
import { dayjs, ElUpload } from "element-plus";
import { UPLOAD_IMAGE_URL } from "@/api/images";
import { ImageItem } from "types/image";
import {
  FlowerMaterial,
  FlowerOccasion,
  FlowerReceiver,
  FlowerStatus
} from "@/constants";
import { FlowerTypeOptionItem } from "types/flower";
import { isArray } from "@pureadmin/utils";

const SERVER_URL = import.meta.env.VITE_SERVER_URL;

const flowerTypeOptions = ref<OptionsRow[]>([]);
const flowerTypeMap = ref<Record<number, FlowerTypeOptionItem>>([]);

const loadFlowerType = async () => {
  try {
    const response = await getFlowerTypeOptions();
    flowerTypeOptions.value = response.map(item => ({
      label: item.name,
      value: item.id
    }));
    flowerTypeMap.value = response.reduce((map, item) => {
      map[item.id] = item;
      return map;
    }, {});
  } catch (error) {
    console.log(error);
  }
};

const tableRef = ref();

const {
  loading,
  columns,
  dataList,
  pagination,
  loadingConfig,
  adaptiveConfig,
  filter,
  onSizeChange,
  onCurrentChange,
  refresh,
  search
} = useColumns({
  onEdit: (row, index) => {
    const data: any = {
      id: row.id,
      name: row.name,
      description: row.description,
      images: row.images,
      original_price: row.original_price,
      price: row.price,
      receiver: row.receiver,
      material: row.material,
      size: row.size,
      type: row.type,
      occasion: row.occasion,
      tags: row.tags,
      presale: row.presale
    };

    if (row.presale) {
      if (row.presale_start_date && row.presale_end_date) {
        data.presale_date = [row.presale_start_date, row.presale_end_date];
      }

      if (row.presale_delivery_start_date && row.presale_delivery_end_date) {
        data.presale_delivery_date = [
          row.presale_delivery_start_date,
          row.presale_delivery_end_date
        ];
      }
    }

    formData.value = data;

    formVisible.value = true;
  },
  onDelete: async (row, index) => {
    try {
      await deleteFlower(row.id);
      message("删除成功", { type: "success" });
      refresh();
    } catch (e) {
      if (e.response.data && e.response.data.message) {
        message(e.response.data.message, { type: "error" });
      } else {
        message("删除失败", { type: "error" });
      }
      console.log(e);
    }
  }
});

const formRules = {
  name: [
    {
      required: true,
      message: "请输入名称"
    }
  ],
  type: [
    {
      required: true,
      message: "请选择分类"
    }
  ],
  quantity: [
    {
      required: true,
      message: "请输入库存"
    }
  ],
  original_price: [
    {
      required: true,
      message: "请输入原价"
    }
  ],
  price: [
    {
      required: true,
      message: "请输入价格"
    }
  ],
  status: [
    {
      required: true,
      message: "请选择状态"
    }
  ],
  presale_date: [
    {
      required: true,
      message: "请输入预售时间"
    }
  ]
};

onBeforeMount(async () => {
  await loadFlowerType();
});

const submitLoading = ref<boolean>(false);
const formVisible = ref(false);
const formData = ref<FieldValues>({});
const formColumns: PlusColumn[] = [
  {
    label: "名称",
    prop: "name",
    valueType: "input"
  },
  {
    label: "描述",
    prop: "description",
    valueType: "textarea"
  },
  {
    label: "枝数",
    prop: "size",
    valueType: "input-number",
    colProps: {
      span: 12
    }
  },
  {
    label: "对象",
    prop: "receiver",
    valueType: "select",
    options: FlowerReceiver,
    colProps: {
      span: 12
    }
  },
  {
    label: "花材",
    prop: "material",
    valueType: "select",
    options: FlowerMaterial,
    colProps: {
      span: 12
    }
  },
  {
    label: "场合",
    prop: "occasion",
    valueType: "select",
    options: FlowerOccasion,
    colProps: {
      span: 12
    }
  },
  {
    label: "分类",
    prop: "type",
    valueType: "select",
    options: computed(() => flowerTypeOptions.value),
    colProps: {
      span: 12
    }
  },
  {
    label: "原价",
    prop: "original_price",
    valueType: "input-number",
    colProps: {
      span: 12
    }
  },
  {
    label: "售价",
    prop: "price",
    valueType: "input-number",
    colProps: {
      span: 12
    }
  },
  {
    label: "标签",
    prop: "tags",
    valueType: "plus-input-tag"
  },
  {
    label: "鲜花图片",
    prop: "images",
    valueType: "img",
    tooltip: "第一张图片将作为封面",
    renderField(value: string[], onChange) {
      const images = isArray(value) ? value : [];
      console.log(images);
      return h(Fragment, [
        h(
          ElUpload,
          {
            fileList: images.map(item => ({
              name: item,
              url: SERVER_URL + item
            })),
            action: UPLOAD_IMAGE_URL,
            listType: "picture-card",
            onSuccess: async (data: ImageItem) => {
              console.log(data);
              onChange([
                ...value,
                `/static/images/${data.folder}/${data.hash}.${data.format}`
              ]);
            },
            onRemove(uploadFile, uploadFiles) {
              console.log(uploadFile, uploadFiles);
              onChange(uploadFiles.map(item => item.name));
            }
          },
          [h(IconifyIconOnline, { icon: "ep:plus" })]
        )
      ]);
    }
  },
  {
    label: "预售",
    prop: "presale",
    valueType: "switch",
    colProps: {
      span: 24
    }
  },
  {
    label: "预售时间",
    prop: "presale_date",
    valueType: "date-picker",
    fieldProps: {
      type: "daterange",
      onChange: () => {
        formData.value.presale_delivery_date = null;
      }
    },
    colProps: {
      span: 12
    },
    hideInForm: computed(() => !formData.value.presale)
  },
  {
    label: "预售发货时间",
    prop: "presale_delivery_date",
    valueType: "date-picker",
    fieldProps: {
      type: "daterange",
      disabledDate: time => {
        if (formData.value.presale_date) {
          return dayjs(time) < dayjs(formData.value.presale_date[1]);
        }
        return false;
      }
    },
    colProps: {
      span: 12
    },
    hideInForm: computed(() => !formData.value.presale)
  }
];

const handleNew = () => {
  formData.value = {
    images: [],
    presale: false
  };
  formVisible.value = true;
};

const handleConfirm = async e => {
  try {
    submitLoading.value = true;
    if (e.presale) {
      if (e.presale_date) {
        e.presale_start_date = dayjs(e.presale_date[0]).startOf("day");
        e.presale_end_date = dayjs(e.presale_date[1]).endOf("day");
      }

      if (e.presale_delivery_date) {
        e.presale_delivery_start_date = dayjs(
          e.presale_delivery_date[0]
        ).startOf("day");
        e.presale_delivery_end_date = dayjs(e.presale_delivery_date[1]).endOf(
          "day"
        );
      }
    }

    if (formData.value.id) {
      await updateFlower(e);
    } else {
      await createFlower(e);
    }
    message("保存成功", { type: "success" });
    formVisible.value = false;
    refresh();
  } catch (e) {
    if (e.response.data && e.response.data.message) {
      message(e.response.data.message, { type: "error" });
    } else {
      message("保存失败", { type: "error" });
    }
    console.log(e);
  } finally {
    submitLoading.value = false;
  }
};

const handleSearch = e => {
  search();
};
</script>
<template>
  <div>
    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between items-center">
          <span>鲜花管理</span>

          <el-space>
            <el-radio-group v-model="filter.presale" @change="refresh">
              <el-radio-button label="全部" :value="false" />
              <el-radio-button label="预售" :value="true" />
            </el-radio-group>

            <el-input
              v-model="filter.kw"
              style="width: 240px"
              clearable
              placeholder="请输入关键词"
              @change="handleSearch"
            >
              <template #append>
                <IconifyIconOnline icon="ep:search" />
              </template>
            </el-input>
            <el-button type="primary" @click="handleNew">
              <template #icon>
                <IconifyIconOnline icon="ep:plus" />
              </template>
              新增
            </el-button>
          </el-space>
        </div>
      </template>
      <pure-table
        ref="tableRef"
        border
        adaptive
        :adaptiveConfig="adaptiveConfig"
        row-key="id"
        alignWhole="center"
        showOverflowTooltip
        :loading="loading"
        :loading-config="loadingConfig"
        :data="dataList"
        :columns="columns"
        :pagination="pagination"
        @page-size-change="onSizeChange"
        @page-current-change="onCurrentChange"
      />
    </el-card>
    <PlusDialogForm
      v-model:visible="formVisible"
      v-model="formData"
      :destroy-on-close="true"
      :title="formData.id ? '编辑鲜花' : '添加鲜花'"
      :form="{
        columns: formColumns,
        rules: formRules,
        labelPosition: 'top',
        rowProps: {
          gutter: 12
        }
      }"
      :confirmLoading="submitLoading"
      @confirm="handleConfirm"
    />
  </div>
</template>
